var navCollapse = 1,collapse_score = true;

$(function(){
	$.fn.center=function(){
		$(this).css("position","fixed");
		var h = ($(window).height()/2) - (this.outerHeight(true)/2);
		var w = ($(window).width()/2) - ($(this).outerWidth(true)/2);
		this.css("top",h);$(this).css("left",w);return $(this);
	};
	
	$("#unityPlayer").css({
		width:1024,
		height:$(window).height() - 60
	});
	
	$("#unityPlayer .missing").center();
	
	$("#my-score > div > span").click(function(){
		var obj = $("#my-score");
		if(collapse_score){
			obj.stop(true,true).animate({
				left: -obj.width() + 30
			},600);
			$(this).attr("title","Hiện bảng điểm").removeClass('glyphicon-resize-small').addClass('glyphicon-resize-full');
		}else{
			obj.stop(true,true).animate({
				left: 0
			},600);
			$(this).attr("title","Ẩn bảng điểm").removeClass('glyphicon-resize-full').addClass('glyphicon-resize-small');;
		}
		collapse_score = !collapse_score;
	});
	
	$("#services-slide ul li").hover(function(){
		var offset = $(this).offset();
		var tooltip = $(".box-tooltip");
		$(".box-tooltip").html("<div><span class='arrow-down'></span>" + $(this).children("div").html() + "</div>");
		tooltip.css({
			left: (offset.left - tooltip.outerWidth()/2) + ($(this).outerWidth()/2),
			zIndex:9999
		}).stop(true,true).stop(true,true).show();
		tooltip.removeClass("fadeInDown animated").addClass('fadeInDown animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
				$(this).removeClass("fadeInDown animated");
			});
	},function(){		
		$(".box-tooltip").stop(true,true).hide("fast");
		$(".box-tooltip").html("");
	});
	
	$("#form_login").center();
	$("#list-games").center();
	
	navCollapse = readCookie('navCollapse');
	if(navCollapse === null) navCollapse = 1;
	if(navCollapse == 1){
		$("#navigation").stop(true,true).animate({
			top: 0
		},400);
		$("#nav-collapse a").attr("title","Hiện menu").css("background-image","url(" + home_url + "/images/pull-up.png)");
		navCollapse = 1;
	}else{
		$("#navigation").stop(true,true).animate({
			top: "-60px"
		},400);
		$("#nav-collapse a").attr("title","Ẩn menu").css("background-image","url(" + home_url + "/images/pull-down.png)");
		navCollapse = 0;
	}
	
	$("#nav-collapse a").click(function(){
		navCollapse = !navCollapse;
		if(navCollapse){
			$("#navigation").stop(true,true).animate({
				top: 0
			},400);
			$(this).attr("title","Hiện menu").css("background-image","url(" + home_url + "/images/pull-up.png)");
			navCollapse = 1;
		}else{
			$("#navigation").stop(true,true).animate({
				top: "-60px"
			},400);
			$(this).attr("title","Ẩn menu").css("background-image","url(" + home_url + "/images/pull-down.png)");
			navCollapse = 0;
		}
		createCookie("navCollapse",navCollapse,1);
		return false;
	});
	
	$("#services-slide ul").carouFredSel({
		auto : true,
		align: "center",
		prev: {
			button: "#prev-services-slide",
		},
		next: {
			button: "#next-services-slide",
		},
		items: "7",
		direction           : "left",
		scroll : {
			items           : "7",
			duration        : 800,
			pauseOnHover    : true
		}
	});
	var wItem = $("#services-slide ul li").outerWidth();
	var allItem = $("#services-slide ul li").size();
	$("#services-slide .caroufredsel_wrapper").css({
		width: allItem * wItem,
		margin:"auto"
	});
});

function readCookie(name) {
	var cookiename = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(cookiename) == 0) return c.substring(cookiename.length,c.length);
	}
	return null;
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function removeCookie(name) {
    createCookie(name,"",-1);
}

if(router == 'test')
	var app = angular.module("apps", ['angularUtils.directives.dirPagination']);
else
	var app = angular.module("apps", []);
/*
app.config(function($httpProvider) {
	//Enable cross domain calls
	$httpProvider.defaults.useXDomain = true;

	//Remove the header used to identify ajax call  that would prevent CORS from working
	delete $httpProvider.defaults.headers.common['X-Requested-With'];
});*/
app.controller("loginController", function($scope){
	
});

app.controller("listGameController", function($scope){
	
});
app.directive("testDirective",function(){
	return function(scope,element,attrs){
		if(scope.$index){
			setTimeout(function(){
				scope.$emit("testDirective",element,attrs);
			},10);
		}
	}
})
.controller("rankingController", function($scope,$http){

	$scope.$on("testDirective",function(scope,element,attrs){
		var f = angular.element("#ranking .rank").first();
		var i = element.find("td:first-child").text();
		var v = parseInt(f.text());
		if(v == 1){
			f.empty().html("<i class='fa fa-trophy r1'></i>");
		}else if(v == 2){
			f.empty().html("<i class='fa fa-trophy r2'></i>");
		}else if(v == 3){
			f.empty().html("<i class='fa fa-trophy r3'></i>");
		}else if(v > 3 && v <= 10 ){
			f.empty().html("<i class='fa fa-star top10'></i>");
		}else{
			f.remove("i");
		}
		if(i == 2){
			element.find(".rank").empty().html("<i class='fa fa-trophy r2'></i>");
		}else if(i == 3){
			element.find(".rank").empty().html("<i class='fa fa-trophy r3'></i>");
		}else if(i > 3 && i <= 10 ){
			element.find(".rank").empty().html("<i class='fa fa-star'></i>");
		}else{
			element.find("td").first().remove("i");
		}
		//if(parseInt(r1.text()) ==)
	});
	
	$scope.list = {};
	$scope.types =[
		{value: 'name', display: 'Tên'},
		{value: 'phone',display: 'Số điện thoại'},
		{value: 'email',display: 'Email'},
		{value: 'game',display: 'Games'},
		{value: 'score',display: 'Điểm'},
		{value: 'department',display: 'Phòng ban'},
	];
	
	$scope.list_games =[
		{id: '1', name: 'Cặp đôi hoàn hảo'},
		{id: '2', name: 'Ai là triệu phú'}
	];
	
	$scope.list_choise = $scope.list_games;
	$scope.list_departments = {};
	
	$scope.current_filter = $scope.types[3];
	$scope.current_select = $scope.list_games[0];
	$scope.show_me = 1;
	$scope.keyword = $scope.current_select.id;
	$scope.empty_list = 0;
	$scope.list_week = [{name: 'Tuần 1',value: 1}];
	$scope.current_week = $scope.list_week[0];
	$scope.url = home_url + "/api.php?";
	
	$scope.change_week = function(){
		
	};
	
	$scope.listWeek =function(){
		$http.get($scope.url + "f=list_week")
		.success(function(response){
			$scope.list_week = response;
			$scope.current_week = $scope.list_week[current_week -1];
		});
	};
	setTimeout(function(){
		$scope.listWeek();
	},100);
	
	$scope.change_select = function(){
		$scope.keyword = $scope.current_select.id;
		if($scope.current_select.id == '0')
			balloon_title = 'Phòng ban';
		else
			balloon_title = 'Người chơi';
		console.log(balloon_title);
	};
	
	$scope.change_filter = function(){
		balloon_title = 'Người chơi';
		if($scope.current_filter.value == 'game'){
			$scope.show_me = 1;
			$scope.list_choise = $scope.list_games;
			$scope.current_select = $scope.list_games[0];
			$scope.keyword = $scope.current_select.id;
			
		}else if($scope.current_filter.value == 'department'){
			$scope.show_me = 1;
			$scope.list_choise = $scope.list_departments;
			$scope.current_select = $scope.list_choise[0];
			$scope.keyword = $scope.current_select.id;
			balloon_title = 'Phòng ban';
		}else{
			$scope.show_me = 0;
			$scope.keyword = "";
		}
		//console.log($scope.url + "f=ranking&t=" + $scope.current_filter.value + "&k=" + $scope.keyword);
	};
	
	$scope.departments = function(){
		$http.get($scope.url + "f=department")
			 .success(function(response){
				setTimeout(function(){
					$scope.list_departments = response;
				},1000);
			 });
	};
	$scope.departments();
	
	$scope.search = function(){
		console.log($scope.url + "w=" + $scope.current_week.value + "&f=ranking&t=" + $scope.current_filter.value + "&k=" + $scope.keyword);
		$http.get($scope.url + "w=" + $scope.current_week.value + "&f=ranking&t=" + $scope.current_filter.value + "&k=" + $scope.keyword)
		.success(function(response){
			if(response !== null){
				$scope.list = response;
				$scope.show_list = 1;
			}else{
				$scope.show_list = 0;
			}
			if(listData != null && typeof chart !== 'undefined'){
				chart.startDuration = 1;
				chart.sequencedAnimation = true;
				chart.startEffect = "bounce";
				chart.dataProvider = response;
				chart.validateData();
				chart.animateAgain();
			}else{
				listData = $scope.list
			}
		})
		.error(function(data, status, headers, config){
			console.log("ERROR!: status");
			console.log("Status: " + status);
		});
	};
	setTimeout(function(){
		$scope.search();
	},500);
	
});

app.controller("gameController", function($scope,$http){
	$scope.myInfo ={};
	/*
	$http.get(home_url + "/getUserInfo.php")
	.success(function(response){
		$scope.myInfo = response;
	});
	*/	
	$scope.updateScore = function(){
		$http.get(home_url + "/getUserInfo.php")
		.success(function(response){
			$scope.myInfo = response;
			console.log("refresh successful!");
		});
	};
	$scope.updateScore();
});

app.controller("accountController", function($scope){
	
});

app.controller("dashBoardController", function($scope){
	
});

app.controller("servicesController", function($scope){
	
});

function testController($scope,$http){
	$scope.currentPage = 1;
	$scope.pageSize = 10;
	$scope.meals = [];
	$scope.totalItems = $scope.meals.length;
	
	$scope.test = function(){
		$http.get("http://localhost/event_game/api.php?w=1&f=department")
			 .success(function(response){
				$scope.meals = response;
				console.log($scope.meals);
			 });
	};
	$scope.test();

	$scope.pageChangeHandler = function(num) {
	  console.log('meals page changed to ' + num);
	};
};